package com.whut.imservice.ws.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Description: 自动关闭没有心跳的连接
 * @Author: Zonghe Wang
 * @Date: 2025/5/24 20:07
 */
@ChannelHandler.Sharable
@Component
@RequiredArgsConstructor
public class CloseIdleChannelHandler extends ChannelDuplexHandler {
    private static final Logger logger = LoggerFactory.getLogger(CloseIdleChannelHandler.class);

    private final WebsocketRouterHandler websocketRouterHandler;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) {
                logger.info("connector no receive ping packet from client,will close.,channel:{}", ctx.channel());
                websocketRouterHandler.cleanupChannel(ctx.channel());
                ctx.close();
            }
        }
    }
}
